package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 统计指定时间内的营业额
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //创建集合用来存储这个时间段的时间数据
        List<LocalDate> dateList = new ArrayList<>();
        //开始时间
        dateList.add(begin);
        //中间时间 begin+1
        while (!begin.equals(end)) {
            //如果开始时间不等于结束时间  则天数+1
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //创建金额的集合
        List<Double> turnoverList = new ArrayList<>();
        //将天数集合遍历
        for (LocalDate date : dateList) {
            //当天开始时间 最小值
            LocalDateTime minDateTime = LocalDateTime.of(date, LocalTime.MIN);
            //当天结束时间  最大值
            LocalDateTime maxDateTime = LocalDateTime.of(date, LocalTime.MAX);

            //根据map来存储三个值
            HashMap map = new HashMap();
            map.put("begin", minDateTime);
            map.put("end", maxDateTime);
            map.put("status", Orders.COMPLETED);

            //根据当天最小值，和最大值，和已完成订单条件来查询订单的总金额
            Double money = orderMapper.sumByMin_MaxAndStatus(map);
            money = money == null ? 0.0 : money;

            turnoverList.add(money);
        }

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();

    }

    /**
     * 用户统计接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //创建日期集合
        List<LocalDate> dateList = new ArrayList<>();
        //添加初始日期
        dateList.add(begin);
        //判断开始时间和结束时间是否相同，不相同+1
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //创建新增用户列表集合
        List<Integer> newUserList = new ArrayList<>();
        //创建总用户量列表集合
        List<Integer> totalUserList = new ArrayList<>();
        //遍历日期集合
        for (LocalDate date : dateList) {
            //获取当前日的开始时间和结束时间
            LocalDateTime startTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询用户表
            HashMap map = new HashMap();
            map.put("end", endTime);
            //获取当前日新增用户
            Integer newUserNum = userMapper.getUserByTime(map);
            //获取总用户的数量
            map.put("start", startTime);
            Integer totalUserNum = userMapper.getUserByTime(map);
            newUserList.add(newUserNum);
            totalUserList.add(totalUserNum);
        }
        //返回给前端
        UserReportVO reportVO = UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
        return reportVO;
    }


    /**
     * 订单统计接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //创建日期集合
        List<LocalDate> dateList = new ArrayList<>();
        //添加开始时间
        dateList.add(begin);
        //添加后面的时间
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //创建订单总数集合
        List<Integer> orderCountList = new ArrayList<>();
        //创建有效订单总数集合
        List<Integer> validOrderCountList = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;

        //遍历日期
        for (LocalDate date : dateList) {
            //获取开始时间和结束时间
            LocalDateTime startTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //获取当天的订单总数
            HashMap map = new HashMap();
            map.put("start", startTime);
            map.put("end", endTime);
            //当天总订单数
            Integer orderCount = orderMapper.getNumByTimeAndStatus(map);
            map.put("status", Orders.COMPLETED);
            //当天有效订单数
            Integer validOrder = orderMapper.getNumByTimeAndStatus(map);
            //总订单数
            orderCountList.add(orderCount);
            //总有效订单数
            validOrderCountList.add(validOrder);

            //通过stream流来遍历查询总数
            totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
            //通过stream流来遍历查询有效订单总数
            validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        }

        //订单完成率
        Double orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;


        OrderReportVO reportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .build();
        return reportVO;


    }


    /**
     * top10排名接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        //获取每日开始时间，结束时间
        LocalDateTime startTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        //查询top10  获取菜品名  菜品销量
        List<GoodsSalesDTO> goodsSalesList = orderMapper.top10(startTime, endTime);

        log.info("top10集合：{}", goodsSalesList);
        //通过stream流获取菜品  和菜品销量
        String dishNameList = StringUtils.join(goodsSalesList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()), ",");
        String dishNumList = StringUtils.join(goodsSalesList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()), ",");

        //返回给前端
        SalesTop10ReportVO top10ReportVO = SalesTop10ReportVO.builder()
                .nameList(dishNameList)
                .numberList(dishNumList)
                .build();
        return top10ReportVO;
    }

    /**
     * 到处运营数据报表
     *
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) {
        //查询数据库获取营业数据  最近30天
        //开始日期
        LocalDate beginDate = LocalDate.now().minusDays(30);
        LocalDateTime beginTime = LocalDateTime.of(beginDate, LocalTime.MIN);
        //结束日期
        LocalDate endDate = LocalDate.now().minusDays(1);
        LocalDateTime endTime = LocalDateTime.of(endDate, LocalTime.MAX);

        //概览数据
        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);

        //将数据库写入excel中

        //获取模板的路径
        InputStream input = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于模板文件创建新的excel文件
            XSSFWorkbook excel = new XSSFWorkbook(input);
            //填充数据
            //获取excel表格标签页
            XSSFSheet sheet = excel.getSheet("sheet1");
            //获取行然后添加值 --时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + beginDate + "至" + endDate);
            //第四行  第三个 营业额  第五个 订单完成率  第七个 新增用户数
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            //第五行  第三个 有效订单  第五个  平均客单价
            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

            //填充三十天的每天数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = beginDate.plusDays(i);
                //查询某一天的数据
                BusinessDataVO bd = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                XSSFRow row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date + "");
                row.getCell(2).setCellValue(bd.getTurnover());
                row.getCell(3).setCellValue(bd.getValidOrderCount());
                row.getCell(4).setCellValue(bd.getOrderCompletionRate());
                row.getCell(5).setCellValue(bd.getUnitPrice());
                row.getCell(6).setCellValue(bd.getNewUsers());
            }

            //通过输出流将excel下载到客户端
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);


            //释放资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}
